package com.flutter.flutter_comm100

import android.app.Activity
import android.content.Intent
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry


/** FlutterComm100Plugin */
class FlutterComm100Plugin : FlutterPlugin, ActivityAware,
    PluginRegistry.ActivityResultListener {

    private lateinit var mActivity: Activity
    private lateinit var mFlutterPluginBinding: FlutterPlugin.FlutterPluginBinding
    private var factory: ClientComm100ViewFactory? = null
    private var activityBinding: ActivityPluginBinding? = null

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        mFlutterPluginBinding = flutterPluginBinding
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        mActivity = binding.activity
        activityBinding = binding
        activityBinding?.addActivityResultListener(this)
        val messenger: BinaryMessenger = mFlutterPluginBinding.binaryMessenger
        factory = ClientComm100ViewFactory(messenger, mActivity)
        mFlutterPluginBinding
            .platformViewRegistry
            .registerViewFactory(
                "plugins.flutter.io/comm100_view", factory!!)
    }

    override fun onDetachedFromActivityForConfigChanges() {
        tearDown()
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        onAttachedToActivity(binding)
    }

    override fun onDetachedFromActivity() {
        tearDown()
    }

    private fun tearDown() {
        factory = null
        activityBinding?.removeActivityResultListener(this)
        activityBinding = null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        if (requestCode == 1) {
            if (factory != null && factory?.getFlutterWebView() != null) {
                factory?.getFlutterWebView()!!.activityResult(requestCode, resultCode, data)
            }
        }
        return false
    }


}
